package com.lian.community.service.user;

import com.lian.community.constant.EntityType;
import com.lian.community.constant.RedisKeyType;
import com.lian.community.dao.redis.JedisDAO;
import com.lian.community.dao.user.UserDAO;
import com.lian.community.dao.user.po.UserPO;
import com.lian.community.entity.user.HostUser;
import com.lian.community.entity.user.User;
import com.lian.community.service.token.TokenService;
import com.lian.community.util.EncryptionUtil;
import com.lian.community.util.RedisKeyUtil;
import com.lian.community.util.SaltUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Transaction;

import javax.swing.text.html.parser.Entity;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    UserDAO userDAO;
    @Autowired
    HostUser hostUser;
    @Autowired
    JedisDAO jedisDAO;
    @Autowired
    TokenService tokenService;
    private static final int REMEVERME_TIME = 604880;

    /**
     * rememberMe功能
     * @param id
     * @return
     */

    public Integer register(User user){
        String salt = SaltUtil.getSalt();
        byte[] password = EncryptionUtil.getEncryptedBytes(user.getPassword() + salt);
        UserPO userPO = new UserPO();
        userPO.setName(user.getName());
        userPO.setPassword(password);
        userPO.setSalt(salt);
        userDAO.insert(userPO);
        return userDAO.lastInsertId();

    }

    public Map<String,Object> login(User user){
        UserPO userPO = userDAO.selectByName(user.getName());
        Map<String,Object> map = new HashMap<>();
        if(userPO != null){
            Integer id = userPO.getId();
            map.put("id", id);
            boolean flag = Arrays.equals(EncryptionUtil.getEncryptedBytes(user.getPassword()+ userPO.getSalt()), userPO.getPassword());
            if(flag){
                map.put("error", "密码错误");
            }
        }else {
            map.put("error","不存在此用户！");
        }
        return map;
    }
}
